<!-- 申请维修 -->
<template>
  <div class="repair">
    <div class="main">
      <van-cell-group inset class="card">
        <Row  class="fieldBox">
          <Col span="24">
            <!-- 设备流水号 --><!-- placeholder="请输入或扫一扫" -->
            <van-field :label="$t('fault.SerialNo')" input-align="right" clearable v-model="form.deviceMId" :placeholder="$t('fault.enterScan')" />
          </Col>
<!--          <Col span="3" class="scanBox">-->
<!--            <img  src="@/assets/imgs/list/scan.png" class="scan"  @click="scanCode"/>-->
<!--          </Col>-->
        </Row>
        <!-- 设备编号 --><!-- placeholder="根据设备流水号自动带出" -->
        <van-field :label="$t('fault.EquipmentNo')" input-align="right" clearable v-model="form.deviceNo"  :placeholder="$t('fault.Automatically')"
          disabled />
          <!-- 设备名称 --><!-- placeholder="根据设备流水号自动带出" -->
        <van-field  :label="$t('fault.EquipmentName')" input-align="right" clearable v-model="form.deviceName"  :placeholder="$t('fault.Automatically')"
          disabled />
      </van-cell-group>
      <van-cell-group inset class="card ">
            <!-- 故障时间 --> <!-- placeholder="点击选择时间" -->
        <van-field :label="$t('fault.FaultTime')"
                   readonly input-align="right"
                   clickable name="datetimePicker"
                   >
          <template #extra>
            <DatePicker
                       :transfer="true"
                        type="datetime"
                        :placeholder="$t('fault.SelectTime')"
                        style="width: 210px"
                        @on-ok="timeConfirm"
            />
          </template>
        </van-field>
<!--        <van-popup v-model="timeShowPicker" position="bottom">-->
<!--          <van-datetime-picker type="datetime" @confirm="timeConfirm" @cancel="timeShowPicker = false"-->
<!--            :min-date="minDate" :max-date="maxDate" :formatter="formatter" v-model="currentDate" />-->
<!--        </van-popup>-->
          <!-- 报修日期 --><!-- placeholder="点击选择时间" -->
        <van-field :label="$t('fault.ApplyDate')"
                   readonly input-align="right"
                   clickable name="datetimePicker"
                    >
          <template #extra>
            <DatePicker
                type="date"
                :transfer="true"
                :placeholder="$t('fault.SelectTime')"
                style="width: 210px"
                @on-change="dateConfirm"
            />
          </template>
        </van-field>
<!--        <van-popup v-model="dateShowPicker" position="bottom">-->
<!--          <van-datetime-picker type="date" @confirm="dateConfirm" @cancel="dateShowPicker = false" :min-date="minDate"-->
<!--            :formatter="formatter" v-model="currentDate" />-->
<!--        </van-popup>-->
       <!-- 报修人 -->
        <van-field :label="$t('fault.AppliedBy')" input-align="right" clearable v-model="form.username"  disabled />
       <!-- 报修电话 -->
      <van-field :label="$t('fault.PhoneNumber')" input-align="right" clearable v-model="form.maintainApplyPhone"  :placeholder="$t('fault.PleaseEnter')" />
        <van-popup input-align="right" clearable v-model="form.showPicker" position="bottom">
          <van-datetime-picker type="datetime" clearable @confirm="onConfirm" @cancel="showPicker = false"
            :min-date="minDate" :formatter="formatter" v-model="currentDate" />
        </van-popup>
         <!-- 维修迫切程度 -->
        <van-field :label="$t('fault.Priority')" name="radio" clearable >
          <template #input>
            <van-radio-group v-model="maintainGrade" direction="horizontal" checked-color="#035BEB ">
              <van-radio name="2">{{ $t('fault.ExtraUrgent') }}</van-radio>   <!-- 特急 -->
              <van-radio name="1">{{ $t('fault.Urgent') }}</van-radio>   <!-- 紧急 -->
              <van-radio name="0">{{ $t('fault.Normal') }}</van-radio>   <!-- 一般 -->
            </van-radio-group>
          </template>
        </van-field>
         <!-- 是否影响生产 -->
        <van-field :label="$t('fault.ImpactProduction')" name="switch" input-align="right" >
          <template #input>
            <van-switch v-model="affectProductionFlag" size="20" @click="handleSwitch" @change="changeSwitch" />
          </template>
        </van-field>
      </van-cell-group>

      <van-cell-group inset class="card upLoad">
         <!-- 故障现象 -->
        <p class="fieldTitle">{{$t('fault.Description')}}</p>
        <!--请进行描述  -->
        <van-field clearable v-model="form.faultMessage" rows="2" autosize type="textarea" :placeholder="$t('fault.PleaseDescribe')" />
        <up-load :fileListArrVal="fileListArrVal" :fileListVal="fileListVal" @handelDelFujian="handelDelFujian">
        </up-load>
      </van-cell-group>
         <!-- cancel-text="取消" -->
      <van-action-sheet v-model="sheetShow" :actions="actions" @select="onSelect" :cancel-text="$t('maintenance.Cancle')"
        close-on-click-action />
    </div>
   
    <div class="footer">
        <!-- 取消 -->
      <van-button type="primary" round class="btn cancelBtn" @click="cancleBack">{{$t('common.Cancel')}}</van-button>
     <!-- 提交主管确认 -->
     <van-button type="info" round class="btn notClickBtn" @click="submit">{{$t('fault.Submit')}}</van-button>
    </div>
     </div>

</template>

<script>
import { getDeviceListinfo,addWorkOrder } from '@/api/maintenance'
import upLoad from "../components/upLoad";
import moment from "moment";
export default {
  name: "logon",
  components: {
    upLoad
  },
  props: ['tarGetid'],
  data() {
    return {
      //title: "申请维修",
      title: `${this.$t('fault.ApplyForMaintenance')}`,
      userId: "",
      userCode: "",
      userName: "",
      phone: "",
      value: "",
      radio: 1,
      switchChecked: false,
      message: "",
      showPicker: false,
      uploadList: [],
      maintainGrade: "0",
      affectProductionFlag: false,
      form: {
        username: "",
        deviceMId: "",
        deviceNo: "",
        deviceName: "",
        maintainGrade: "0",
        affectProductionFlag: false,
        faultTime: "",
        //maintainApplyDate:moment(new Date()).format("YYYY-MM-DD HH:mm:ss")
      },
      fileListVal: [],
      fileListArrVal: [],
      videoList: [],
      photoList: [],
      timeShowPicker: false,
      dateShowPicker: false,
      sheetShow: false,
      //actions: [{ name: '拍照' }, { name: '视频' },],
      actions: [{ name: `${this.$t('fault.photograph')}` }, { name: `${this.$t('fault.video')}` },],
      minDate: new Date(2020, 0, 1),
      maxDate:new Date(),
      currentDate: new Date(),
    };
  },

  created() {
    this.form.username = window.localStorage.getItem('ziyunFactoryPortalName')
  },

  watch: {
    'form.deviceMId': {
      handler(newVal, oldVal) {
        this.getDevice()
      },
      deep: true
    }
  },


  mounted() {
    if (this.tarGetid) {
      this.form.deviceMId = this.tarGetid
      this.getDevice()
    }
    window.WebViewBridge = {
      onMessage: this._onMessage //在window上挂载一个onMessage方法，RN会调用
    }
    const event = new Event('WebViewBridge')
    window.dispatchEvent(event);
  },

  methods: {
    onConfirm(val) {
      this.showPicker = false
      this.value = moment(val).format("YYYY-MM-DD HH:mm:ss")
    },
    // afterRead(file) {
    //   console.log(file);
    //   try {
    //     let { data, code, msg } = upLoad(file);
    //     alert("data123" + JSON.stringify(file));
    //     if (code == "200") {
    //       this.form.attachmentDTOs.push(data)
    //       alert("attachmentDTOscode" + JSON.stringify(this.form.attachmentDTOs));
    //     } else {
    //       this.$Message.warning(msg);
    //     }

    //   } catch (e) {
    //     console.log("e : ", e);
    //   } finally {

    //   }

    // },
    async getDevice() {
      if (this.form.deviceMId == "") {
        this.form.deviceNo = ""
        this.form.deviceName = ""
        return
      }
      let param = {
        assetsNo: '',
        deviceMId: this.form.deviceMId,
        deviceNo: "",
        orgCode: ""
      };
      try {
        let { data, code, msg } = await getDeviceListinfo(param);
         if (data && data.length){
           const deviceStatus = data.find(val=>val.deviceMId === this.form.deviceMId).deviceStatus
           if (deviceStatus === 3){
             let timeId = setTimeout(()=>{
               this.form.deviceMId = ''
               clearTimeout(timeId)
             },666)
             this.$Message.warning('当前设备已报废!');
             return
           }
         }
        if (code == "200") {
          if (data.length > 0) {
            this.$set(this.form, 'deviceNo', data[0].deviceNo)
            this.$set(this.form, 'deviceName', data[0].deviceName)
          }
        } else {
          this.$Message.warning(msg);
        }
      } catch (e) {

        console.log("e : ", e);
      } finally {
      }
    },
    onOversize() { },
    async scanCode() {
      let param = {
        type: "scan",
      }
      await window.ReactNativeWebView.postMessage(JSON.stringify(param));
      this.getDevice()
    },
    handleVideophoto() {
      this.sheetShow = true
    },
    timeConfirm(time) {
      this.form.faultTime = moment(time).format("YYYY-MM-DD HH:mm:ss")
      // this.timeShowPicker = false;
    },
    dateConfirm(time) {
      this.form.maintainApplyDate = moment(time).format("YYYY-MM-DD HH:mm:ss")
      // this.dateShowPicker = false;
    },

    _onMessage(data) {
      const objInfo = JSON.parse(JSON.stringify(data))
      if (objInfo.type === "scan") {
        this.$set(this.form, 'deviceMId', objInfo.value)
      }
      if (objInfo.type === "video") {
        this.$set(this.videoList, this.videoList.length, objInfo.value)
        //alert("videoList" + JSON.stringify(this.videoList));
      }
      if (objInfo.type === "photo") {
        this.$set(this.photoList, this.photoList.length, objInfo.value)
        //alert("photoList" + JSON.stringify(this.photoList));

        //let a = upLoad(this.photoList)
        //alert("aa--" + JSON.stringify(a));
      }
    },

    //是否影响生产
    handleSwitch(val) { },
    changeSwitch(val) { },
    //删除照片视频
    handelDelFujian(val) {
      this.fileListVal = val
    },
    cancleBack(){
      this.$emit('cancleBack')
    },
    async submit() {
      if (this.form.deviceMId == '') {
        //this.$Message.warning("请填写设备流水号");
        this.$Message.warning(`${this.$t('fault.PleaseEnterEquipment')}`);
        return
      }
      if (this.form.faultTime == '') {
        //this.$Message.warning("请选择故障时间");
         this.$Message.warning(`${this.$t('fault.PleaseEnterFailure')}`);
        return
      }
      if (this.form.maintainApplyDate == '') {
       // this.$Message.warning("请选择报修日期");
        this.$Message.warning(`${this.$t('fault.selectRequestDate')}`);
        return
      }
      if (this.form.maintainApplyDate == '') {
        //this.$Message.warning("请输入正确手机号");
         this.$Message.warning(`${this.$t('fault.PleaseEnterPhone')}`);
        return
      }

      if (!(/^(1[3456789]\d{9})$/.test(this.form.maintainApplyPhone)) && !(/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/.test(this.form.maintainApplyPhone))) {
       // this.$Message.warning("请输入正确手机号");
        this.$Message.warning(`${this.$t('fault.PleaseEnterPhone')}`);
        return
      }

      if (this.fileListVal && this.fileListVal.length) {
        const data = this.fileListVal.map(val => ({
          attachmentType: 1,
          fileName: val.fileName,
          filePath: val.filepath,
          fileUrl: val.fileUrl
        }))
        this.form.attachmentDTOs = data
      }
      this.form.maintainApplyBy = window.localStorage.getItem("ziyunFactoryUserId"),
        this.form.maintainGrade = Number(this.maintainGrade)
      this.form.affectProductionFlag = this.affectProductionFlag ? 1 : 0
      let data = { ...this.form };

      try {
        let { msg,code } = await addWorkOrder(data);
        //if (msg == "操作成功") {
          if (code == 200) {
            this.$Message.success('操作成功！')
          this.$router.push({ path: '/maintenanceList' })
        } else {
          this.$Message.warning(msg);
        }
         this.cancleBack()
      } catch (e) {
        console.log("e : ", e);
      } finally {

      }
    },
    onSelect(item) {
      this.sheetShow = false;
      switch (item.name) {
          //case '拍照':
          case  `${this.$t('fault.photograph')}`:
          window.ReactNativeWebView.postMessage(JSON.stringify({ type: "photo", }));
          break;
          //case '视频':
          case `${this.$t('fault.video')}`:
          window.ReactNativeWebView.postMessage(JSON.stringify({ type: "video", }));
          break;
        default:
          break;
      }

    },
    //时间处理
    formatter(type, val) {
      if (type === 'year') {
       // return `${val}年`;
         //this.$Message.warning(`${this.$t('fault.PleaseEnterEquipment')}`);
       return `${val}${this.$t('fault.year')}`;
      } else if (type === 'month') {
        //return `${val}月`;
          return `${val}${this.$t('fault.month')}`;
      }
      else if (type === 'day') {
       // return `${val}日`;
         return `${val}${this.$t('fault.day')}`;
      }
      else if (type === 'hour') {
       // return `${val}时`;
         return `${val}${this.$t('fault.hour')}`;
      }
      else if (type === 'minute') {
        //return `${val}分`;
          return `${val}${this.$t('fault.min')}`;
      }
      //  else {
      //   return `${val}秒`;
      // }
      return val;
    },

  }
}
</script>
<style scoped lang="scss">
::v-deep input::placeholder {
  font-size: 14px;
  color: rgba(0, 20, 45, 0.5000);
}
::v-deep textarea::placeholder {
  font-size: 14px;
  color: rgba(0, 20, 45, 0.5000);
}
::v-deep textarea::placeholder:before {
    content:'';
  display: block;
		// 定义元素位置
		margin-top: 12px;
		margin-right: 20px;
   background-image:url('~@/assets/imgs/list/description.png');
   width: 20px;
   height: 20px;
   background-size: 100% 100%;
}
::v-deep .van-field__label{
font-size: 14px;
color: rgba(0,20,45,0.7000);
}
::v-deep .van-cell{
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    box-sizing: border-box;
    width: 100%;
    padding:12px;
    overflow: hidden;
    background-color: #fff;
}

.repair {

  width: 100%;
   //padding-bottom: 56px;
  .main {
    padding-top: 12px;
    
    .card {
      margin-bottom: 12px;

      .fieldTitle {
        font-size: 14px;
        color: rgba(0,20,45,0.7000);
      }
      .fieldBox{
        display: flex;
        align-items: center;
      .scanBox{
         width: 24px;
        height: 24px;
        line-height: 0;
         .scan{
         width: 100%;
        height: 100%
      }
      }
     }
      .imgBox{
        width: 20px;
        height: 20px;
        position: absolute;
        top: 8px;
        left: 0;
        line-height: 20px;
        display: inline-block;
        img{
          width: 100%;
          height: 100%;
        }
      }
      .picTitle {
        font-size: 14px;
        color: rgba(0, 20, 45, 0.7000);
        padding: 12px 0 12px 0;
        border-top: 1px solid rgba(131, 150, 181, 0.2000);
        margin: 0 12px;
      }

      .upload {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 101px;
        height: 101px;
        background: rgba(131, 150, 181, 0.0800);
        border-radius: 4px;
        border: 1px solid rgba(0, 20, 45, 0.2000);
        font-size: 12px;
        margin-left: 12px;
      }
    }
    .upLoad{
      padding:12px ;
    }
  }
  .footer {
    width: 100%;
    height: 56px;
    background: #FFFFFF;
    display: flex;
    justify-content: flex-end;
    align-items: center;
     // position:fixed;
     //left:0;
     //bottom:0;
    .btn {
      min-width: 112px;
      height: 40px;
      font-size: 14px;
      border-radius: 25px;
      border: none;
    }

    .cancelBtn {
      background: rgba(0, 20, 45, 0.1000);
      color: #00142D;
      margin-right: 8px;
    }

    .confirmBtn {
      font-weight: bold;
      color: #FFFFFF;
      margin-right: 12px;
    }

    .notClickBtn {
      font-weight: bold;
      color: #FFFFFF;
      background: rgba(3, 91, 235, 0.5000);
      margin-right: 12px;
    }
}
}
</style>

